<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ isEdit ? '编辑考试' : '创建考试' }}</span>
      </div>
      
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="考试标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入考试标题"></el-input>
        </el-form-item>
        
        <el-form-item label="教育阶段" prop="educationLevel">
          <el-select v-model="form.educationLevel" placeholder="请选择教育阶段" @change="handleEducationLevelChange" style="width: 100%">
            <el-option label="小学" :value="1"></el-option>
            <el-option label="初中" :value="2"></el-option>
            <el-option label="高中" :value="3"></el-option>
            <el-option label="大学" :value="4"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="学科" prop="subjectId">
          <el-select v-model="form.subjectId" placeholder="请选择学科" filterable style="width: 100%">
            <el-option
              v-for="item in subjectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="试卷" prop="paperId">
          <el-select v-model="form.paperId" placeholder="请选择试卷" filterable @change="handlePaperChange" style="width: 100%">
            <el-option
              v-for="item in paperOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="考试时长" prop="duration">
          <el-input-number v-model="form.duration" :min="1" :max="300" :step="1" :disabled="true"></el-input-number>
          <span class="unit-text">分钟</span>
        </el-form-item>
        
        <el-form-item label="总分" prop="totalScore">
          <el-input-number v-model="form.totalScore" :disabled="true"></el-input-number>
          <span class="unit-text">分</span>
        </el-form-item>
        
        <el-form-item label="考试时间" prop="examTime">
          <el-date-picker
            v-model="examTime"
            type="datetimerange"
            :picker-options="{
              disabledDate(time) {
                return time.getTime() < Date.now() - 8.64e7; // 禁用过去的日期
              }
            }"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd'T'HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
            @change="handleTimeChange"
            style="width: 100%">
          </el-date-picker>
          <div class="time-hint" v-if="!examTime || examTime.length !== 2">
            <span style="color: #E6A23C; font-size: 12px;">请选择考试开始和结束时间</span>
          </div>
        </el-form-item>
        
        <el-form-item label="学校" prop="schoolId">
          <el-select v-model="form.schoolId" placeholder="请选择学校（不选则所有学校可见）" filterable clearable style="width: 100%">
            <el-option
              v-for="item in schoolOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="考试说明">
          <el-input type="textarea" v-model="form.description" placeholder="请输入考试说明" :rows="4"></el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getExamDetail, addExam, updateExam } from '@/api/exam';
import { getAllSubjects } from '@/api/subject';
import { getPaperList, getPaperDetail } from '@/api/paper';
import { getSchoolList } from '@/api/school';

export default {
  name: 'ExamEdit',
  data() {
    return {
      isEdit: false,
      examId: null,
      form: {
        title: '',
        educationLevel: undefined,
        subjectId: undefined,
        paperId: undefined,
        duration: 0,
        totalScore: 0,
        startTime: '',
        endTime: '',
        schoolId: undefined,
        description: ''
      },
      examTime: [],
      rules: {
        title: [
          { required: true, message: '请输入考试标题', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        educationLevel: [
          { required: true, message: '请选择教育阶段', trigger: 'change' }
        ],
        subjectId: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        paperId: [
          { required: true, message: '请选择试卷', trigger: 'change' }
        ],
        startTime: [
          { required: true, message: '请选择考试开始时间', trigger: 'change' }
        ],
        endTime: [
          { required: true, message: '请选择考试结束时间', trigger: 'change' }
        ]
      },
      subjectOptions: [],
      allSubjects: [],
      paperOptions: [],
      schoolOptions: []
    };
  },
  watch: {
    'form.educationLevel': function(val) {
      if (val) {
        this.filterSubjectsByLevel(val);
        this.form.subjectId = undefined;
        this.form.paperId = undefined;
        this.paperOptions = [];
      }
    },
    'form.subjectId': function(val) {
      if (val) {
        this.getPapers();
        this.form.paperId = undefined;
      }
    }
  },
  created() {
    this.examId = this.$route.params.id;
    this.isEdit = !!this.examId;
    
    this.getSubjects();
    this.getSchools();
    
    if (this.isEdit) {
      this.getExamDetail();
    }
  },
  methods: {
    // 获取学科列表
    getSubjects() {
      getAllSubjects().then(response => {
        this.allSubjects = response.data;
        this.filterSubjectsByLevel(this.form.educationLevel);
      });
    },
    // 获取学校列表
    getSchools() {
      getSchoolList(1, 100).then(response => {
        this.schoolOptions = response.data.records.map(school => ({
          value: school.id,
          label: school.name
        }));
      });
    },
    // 根据教育阶段筛选学科
    filterSubjectsByLevel(level) {
      if (!level || !this.allSubjects || this.allSubjects.length === 0) {
        this.subjectOptions = this.allSubjects.map(subject => ({
          value: subject.id,
          label: subject.name
        }));
        return;
      }
      
      const filteredSubjects = this.allSubjects.filter(subject => subject.level === level);
      this.subjectOptions = filteredSubjects.map(subject => ({
        value: subject.id,
        label: subject.name
      }));
      
      // 如果当前选中的学科不在筛选结果中，清空选择
      if (this.form.subjectId) {
        const exists = filteredSubjects.some(subject => subject.id === this.form.subjectId);
        if (!exists) {
          this.form.subjectId = undefined;
          this.form.paperId = undefined;
          this.paperOptions = [];
        }
      }
    },
    // 教育阶段变化时触发
    handleEducationLevelChange(level) {
      this.filterSubjectsByLevel(level);
      this.getPapers();
    },
    // 获取试卷列表
    getPapers() {
      if (!this.form.educationLevel || !this.form.subjectId) {
        this.paperOptions = [];
        return;
      }
      
      // 清空之前的选项
      this.paperOptions = [];
      this.form.paperId = undefined;
      
      const params = {
        educationLevel: this.form.educationLevel,
        subjectId: this.form.subjectId,
        status: 1, // 只获取已发布的试卷
        size: 100
      };
      
      console.log('获取试卷列表，参数:', params);
      getPaperList(params).then(response => {
        console.log('试卷列表返回结果:', response.data);
        if (response.data.records && response.data.records.length > 0) {
          this.paperOptions = response.data.records.map(paper => ({
            value: paper.id,
            label: paper.title,
            duration: paper.duration,
            totalScore: paper.totalScore
          }));
          console.log('处理后的试卷选项:', this.paperOptions);
        } else {
          console.log('未找到符合条件的试卷');
        }
      }).catch(error => {
        console.error('获取试卷列表失败:', error);
      });
    },
    // 试卷变化时触发
    handlePaperChange(paperId) {
      const selectedPaper = this.paperOptions.find(item => item.value === paperId);
      if (selectedPaper) {
        this.form.duration = selectedPaper.duration;
        this.form.totalScore = selectedPaper.totalScore;
      } else {
        // 如果下拉选项中没有找到对应的试卷，直接从API获取试卷详情
        getPaperDetail(paperId).then(response => {
          const paper = response.data;
          if (paper) {
            this.form.duration = paper.duration;
            this.form.totalScore = paper.totalScore;
            
            // 同时更新下拉选项
            const paperOption = {
              value: paper.id,
              label: paper.title,
              duration: paper.duration,
              totalScore: paper.totalScore
            };
            
            if (!this.paperOptions.some(p => p.value === paper.id)) {
              this.paperOptions.push(paperOption);
            }
          } else {
            this.form.duration = 0;
            this.form.totalScore = 0;
          }
        }).catch(() => {
          this.form.duration = 0;
          this.form.totalScore = 0;
          this.$message.error('获取试卷信息失败');
        });
      }
    },
    // 获取考试详情
    getExamDetail() {
      getExamDetail(this.examId).then(response => {
        const examData = response.data;
        this.form = {
          title: examData.title,
          educationLevel: examData.educationLevel,
          subjectId: examData.subjectId,
          paperId: examData.paperId,
          duration: examData.duration,
          totalScore: examData.totalScore,
          startTime: examData.startTime,
          endTime: examData.endTime,
          schoolId: examData.schoolId,
          description: examData.description
        };
        
        this.examTime = [examData.startTime, examData.endTime];
        
        // 加载学科和试卷选项
        this.filterSubjectsByLevel(examData.educationLevel);
        this.getPapers();
        
        // 如果试卷不在选项中，需要单独获取试卷信息
        if (examData.paperId) {
          getPaperDetail(examData.paperId).then(paperRes => {
            const paper = paperRes.data;
            if (paper) {
              const paperOption = {
                value: paper.id,
                label: paper.title,
                duration: paper.duration,
                totalScore: paper.totalScore
              };
              
              if (!this.paperOptions.some(p => p.value === paper.id)) {
                this.paperOptions.push(paperOption);
              }
            }
          });
        }
      });
    },
    // 提交表单
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          // 确保开始时间和结束时间已设置（双重检查）
          if (!this.form.startTime || !this.form.endTime) {
            this.$message.error('请选择考试时间');
            return;
          }
          
          const formData = { ...this.form };
          
          // 检查开始时间是否早于当前时间
          const now = new Date();
          const startTime = new Date(formData.startTime);
          
          if (startTime < now && !this.isEdit) {
            this.$confirm('考试开始时间早于当前时间，是否继续？', '提示', {
              confirmButtonText: '继续',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.saveExam(formData);
            }).catch(() => {});
          } else {
            this.saveExam(formData);
          }
        } else {
          console.log('表单验证失败');
          // 检查是否有时间相关的验证错误
          if (!this.examTime || this.examTime.length !== 2) {
            this.$message.error('请选择完整的考试时间范围');
          }
          return false;
        }
      });
    },
    // 保存考试
    saveExam(formData) {
      console.log('准备提交的表单数据:', formData);
      
      // 创建一个处理后的表单数据副本
      const processedData = { ...formData };
      
      // 格式化日期时间为后端需要的格式
      if (processedData.startTime) {
        // 使用统一的方法处理日期格式
        const startDate = new Date(processedData.startTime);
        // 将日期转为YYYY-MM-DDThh:mm:ss格式
        processedData.startTime = startDate.toISOString().split('.')[0];
      }
      
      if (processedData.endTime) {
        // 使用统一的方法处理日期格式
        const endDate = new Date(processedData.endTime);
        // 将日期转为YYYY-MM-DDThh:mm:ss格式
        processedData.endTime = endDate.toISOString().split('.')[0];
      }
      
      console.log('处理后的表单数据:', processedData);
      console.log('处理后的开始时间:', processedData.startTime);
      console.log('处理后的结束时间:', processedData.endTime);
      
      if (this.isEdit) {
        updateExam(this.examId, processedData).then(() => {
          this.$message.success('更新成功');
          this.$router.push('/exams');
        }).catch((error) => {
          console.error('更新失败详情:', error);
          this.$message.error('更新失败: ' + (error.response?.data?.message || error.message || '未知错误'));
        });
      } else {
        addExam(processedData).then(() => {
          this.$message.success('创建成功');
          this.$router.push('/exams');
        }).catch((error) => {
          console.error('创建失败详情:', error);
          this.$message.error('创建失败: ' + (error.response?.data?.message || error.message || '未知错误'));
        });
      }
    },
    // 取消
    cancel() {
      this.$router.push('/exams');
    },
    // 处理时间变化
    handleTimeChange(val) {
      console.log('时间变更:', val);
      if (val && val.length === 2) {
        // 直接使用el-date-picker提供的格式化后的值
        this.form.startTime = val[0];
        this.form.endTime = val[1];
        
        // 输出转换后的值以便调试
        console.log('转换后开始时间:', this.form.startTime);
        console.log('转换后结束时间:', this.form.endTime);
        
        // 确保开始时间早于结束时间
        const startTime = new Date(this.form.startTime);
        const endTime = new Date(this.form.endTime);
        
        if (startTime >= endTime) {
          this.$message.warning('开始时间必须早于结束时间');
          this.examTime = [];
          this.form.startTime = '';
          this.form.endTime = '';
        }
      } else {
        this.form.startTime = '';
        this.form.endTime = '';
      }
    }
  }
};
</script>

<style scoped>
.unit-text {
  margin-left: 10px;
}

.time-hint {
  margin-top: 5px;
}
</style> 